package com.smartthinking.CICPNL.home.activity;

import java.util.ArrayList;
import java.util.Dictionary;
import java.util.Hashtable;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

import com.smartthinking.CICPNL.R;
import com.smartthinking.CICPNL.R.id;
import com.smartthinking.CICPNL.home.objects.App_ImageLoader;

public class Buscador extends Activity {

	public ListView list;
	public ListAdapter adapter;
	public Dialog progressDialog;
	public App_ImageLoader imageLoader;
	private Intent intent;
	String busqueda = "";
	Utilities util;
	public Integer EVEIDR;

	protected String QRY_BUSCADOR;
	
	public static ArrayList<Dictionary<String,String>> Splash = null;
	public static ArrayList<Dictionary<String,String>> arrPatrocinadores = null;
	public static ArrayList<Dictionary<String,String>> arrExpositores = null;
	public static ArrayList<Dictionary<String,String>> arrPonencias = null;
	public static ArrayList<Dictionary<String,String>> arrPonentes = null;
	public static ArrayList<Dictionary<String,String>> arrCupones = null;
	public static ArrayList<Dictionary<String,String>> arrEventos = null;
	public static ArrayList<Dictionary<String,String>> arrNoticias = null;
	public static ArrayList<Dictionary<String,String>> arrLanzamientos = null;
	public static ArrayList<Dictionary<String,String>> arrGeneral = null;

	public void voidFinish(View V) {
		finish();
	}

	public void abrirMenuLateral(View V) {
		intent = new Intent(Buscador.this, MenuLateral.class);
		startActivity(intent);
	}

	@Override
	public void onBackPressed() {
	}
	
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.ui_listview_sfv);
		
		util = new Utilities();

		TextView Titulo = (TextView) this.findViewById(id.tv_listView_Titulo);
		Titulo.setText(getResources().getString(R.string.modulo_buscar));
		EVEIDR = Utilities.EVE_IDR;
		
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
		EditText txtbusc = (EditText) findViewById(id.et_buscar_buscar);
		txtbusc.setOnEditorActionListener(new OnEditorActionListener() {
		    @Override
		    public boolean onEditorAction(TextView v, int keyCode, KeyEvent event) {
		    	if (event != null&& (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
		    		InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
		    		in.hideSoftInputFromWindow(v.getApplicationWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
			        buscar();
			        return true;
		        }
		        return false;
		    }
		});
		
		//splash
		try{
			String qry = "select a.* from eventos_banners a inner join banners_catalogo b on a.ban_idr = b.ban_idr where a.eve_idr = "+EVEIDR+" and b.ban_nombre = 'SPLASH BUSCAR' ORDER BY b.ban_nombre";
			Splash = Utilities.qry2(getApplicationContext(), qry);
			
	    	if(Splash.size()>0){
	    		Dictionary<String, String> dic = Splash.get(0);
		    	String strPoster = dic.get("ban_url").toString();
			    String strTimer = dic.get("ban_timer").toString();
			    String strPatrocinador = dic.get("pat_idr").toString();
			    if (strPoster.equals("null")) {
			        strPoster = "";
			    }
			    if(strPoster.length()>0){
					intent = new Intent(Buscador.this, Splash2.class);
					Bundle bund = new Bundle();
					bund.putString("PUT_IMG",strPoster);
					bund.putString("PUT_PAT",strPatrocinador);
					bund.putString("PUT_TIME",strTimer);
					intent.putExtras(bund);
					startActivity(intent);
			    }
		    }
		}catch(Exception ex){}
	}

	public void borrar(View v){
		EditText txtbusc = (EditText) findViewById(id.et_buscar_buscar);
		txtbusc.setText("");
		buscar();
	}
	
	public void voidbusqueda(View v){
		new AsyncActividades().execute("contenido");
	}

	public void buscar(){
		String strBusqueda = ((EditText) findViewById(id.et_buscar_buscar)).getText().toString().trim();
		if(!strBusqueda.equals(busqueda)){
			busqueda = strBusqueda;
			if(strBusqueda.length()<=0){
				arrGeneral = new ArrayList<Dictionary<String,String>>();
				list = (ListView) findViewById(R.id.list);
				FavoritosArrayAdapter adapter = new FavoritosArrayAdapter(this, arrGeneral, "");
				list.setAdapter(adapter);
			}else{
				new AsyncActividades().execute("");
			}
		}
	}
	
	
	private class AsyncActividades extends AsyncTask<String, Void, Integer> {

		protected void onPostExecute(Integer in) {
			list = (ListView) findViewById(R.id.list);
			Resources res = getResources();
			FavoritosArrayAdapter adapter = new FavoritosArrayAdapter(Buscador.this, arrGeneral, res.getString(R.string.QRY_SERVLET));
			list.setAdapter(adapter);
			list.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
					muestra_detalle(position);
				}
			});
			progressDialog.dismiss();
		}

		protected void onPreExecute() {
			progressDialog = ProgressDialog.show(Buscador.this, "",getResources().getString(R.string.msg_cargando));
		}

		protected Integer doInBackground(String... urls) {
			String strSQL = "";

	        strSQL = "select b.pat_idr, pat_nombre, pat_logo from patrocinadores_eventos a left outer join patrocinadores b on a.pat_idr = b.pat_idr where a.eve_idr = "+EVEIDR+" and upper(pat_nombre) like upper('%%"+busqueda+"%%') order by pat_nombre";
		    arrPatrocinadores = Utilities.qry2(getApplicationContext(), strSQL);
			
		    strSQL = "select exp_idr, exp_nombre, exp_logo from expositores where eve_idr = "+EVEIDR+" and (upper(exp_nombre) like upper('%%"+busqueda+"%%') or upper(exp_stand) like upper('%%"+busqueda+"%%')) order by exp_nombre";
		    arrExpositores = Utilities.qry2(getApplicationContext(), strSQL);
		    
		    strSQL = "select nen_idr, nen_titulo, nen_titulo_en, nen_foto from ponencias where eve_idr = "+EVEIDR+" and (upper(nen_titulo) like upper('%%"+busqueda+"%%') or upper(nen_titulo_en) like upper('%%"+busqueda+"%%') or upper(nen_ponente) like upper('%%"+busqueda+"%%') or upper(nen_institucion) like upper('%%"+busqueda+"%%')  or upper(nen_especialidad) like upper('%%"+busqueda+"%%') or upper(nen_especialidad_en) like upper('%%"+busqueda+"%%') ) order by nen_titulo";
		    arrPonencias = Utilities.qry2(getApplicationContext(), strSQL);
		    
		    strSQL = "select pon_idr, pon_nombre, pon_paterno, pon_materno, pon_empresa, pon_foto from ponentes where eve_idr = "+EVEIDR+" and (upper(pon_nombre) like upper('%%"+busqueda+"%%') or upper(pon_paterno) like upper('%%"+busqueda+"%%') or upper(pon_materno) like upper('%%"+busqueda+"%%') or upper(pon_empresa) like upper('%%"+busqueda+"%%') ) order by pon_nombre,pon_paterno,pon_materno";
		    arrPonentes = Utilities.qry2(getApplicationContext(), strSQL);
		    
		    strSQL = "select a.cup_idr, a.cup_promocion, a.cup_promocion_en, poi_thumb from cupones a left outer join pois b on a.poi_idr = b.poi_idr where eve_idr = "+EVEIDR+" and (upper(cup_promocion) like upper('%%"+busqueda+"%%') or upper(cup_promocion_en) like upper('%%"+busqueda+"%%')) order by cup_promocion";
		    arrCupones = Utilities.qry2(getApplicationContext(), strSQL);

		    strSQL = "select evs_idr, evs_titulo, evs_titulo_en, evs_foto from eventos_sociales where eve_idr = "+EVEIDR+" and (upper(evs_titulo) like upper('%%"+busqueda+"%%') or upper(evs_titulo_en) like upper('%%"+busqueda+"%%')) order by evs_fecha, evs_inicio, evs_titulo";
		    arrEventos = Utilities.qry2(getApplicationContext(), strSQL);
			
		    strSQL = "select not_idr, sec_idr, not_titulo, not_titulo_en, not_thumb from noticias where (upper(not_titulo) like upper('%%"+busqueda+"%%') or upper(not_titulo_en) like upper('%%"+busqueda+"%%')) order by not_titulo";
		    arrNoticias = Utilities.qry2(getApplicationContext(), strSQL);
		    
		    strSQL = "select lan_idr, lan_titulo, lan_titulo_en, lan_foto from lanzamientos where (upper(lan_titulo) like upper('%%"+busqueda+"%%') or upper(lan_titulo_en) like upper('%%"+busqueda+"%%')) order by lan_titulo";
		    arrLanzamientos = Utilities.qry2(getApplicationContext(), strSQL);
			
		    //Junto todo en un solo arreglo
		    Dictionary<String, String> dic = null;
		    arrGeneral = new ArrayList<Dictionary<String,String>>();
		    
		    if(arrPatrocinadores.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_patrocinios));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrPatrocinadores.size();i++){
			    	dic = arrPatrocinadores.get(i);
			    	dic.put("tipoF","Patrocinadores");
			    	arrGeneral.add(dic);
			    }		    	
		    }

		    if(arrExpositores.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_expositores));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrExpositores.size();i++){
			    	dic = arrExpositores.get(i);
			    	dic.put("tipoF","Expositores");
			    	arrGeneral.add(dic);
			    }		    	
		    }

		    if(arrPonencias.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_programa));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrPonencias.size();i++){
			    	dic = arrPonencias.get(i);
			    	dic.put("tipoF","Ponencias");
			    	arrGeneral.add(dic);
			    }		    	
		    }

		    if(arrPonentes.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_ponentes));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrPonentes.size();i++){
			    	dic = arrPonentes.get(i);
			    	dic.put("tipoF","Ponentes");
			    	arrGeneral.add(dic);
			    }		    	
		    }

		    if(arrCupones.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_cupones));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrCupones.size();i++){
			    	dic = arrCupones.get(i);
			    	dic.put("tipoF","Cupones");
			    	arrGeneral.add(dic);
			    }		    	
		    }

		    if(arrEventos.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_ps));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrEventos.size();i++){
			    	dic = arrEventos.get(i);
			    	dic.put("tipoF","Eventos");
			    	arrGeneral.add(dic);
			    }		    	
		    }

		    if(arrNoticias.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_noticias));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrNoticias.size();i++){
			    	dic = arrNoticias.get(i);
			    	dic.put("tipoF","Noticias");
			    	arrGeneral.add(dic);
			    }
		    }

		    if(arrLanzamientos.size()>0){
			    dic = new Hashtable<String, String>();
			    dic.put("Header", getResources().getString(R.string.modulo_lanzamientos));
			    arrGeneral.add(dic);
			    for(int i=0;i<arrLanzamientos.size();i++){
			    	dic = arrLanzamientos.get(i);
			    	dic.put("tipoF","Lanzamientos");
			    	arrGeneral.add(dic);
			    }
		    }

			return null;
		}
	}
	

	public void fTodos(View v){
		ImageButton btnf = (ImageButton) findViewById(R.id.iv_btn_favoritos);
		ImageButton btnt = (ImageButton) findViewById(R.id.iv_btn_todos);
		if (btnt.getTag() == "0"){
			btnt.setImageResource(R.drawable.lst_btn_todos_act);	
			btnt.setTag("1");
			btnf.setImageResource(R.drawable.lst_btn_favoritos_des);
			btnf.setTag("0");
		}else{
			btnt.setImageResource(R.drawable.lst_btn_todos_des);
			btnt.setTag("0");
			btnf.setImageResource(R.drawable.lst_btn_favoritos_act);	
			btnf.setTag("1");
		}
	}
	
	public void fFavoritos(View v){
		ImageButton btnf = (ImageButton) findViewById(R.id.iv_btn_favoritos);
		ImageButton btnt = (ImageButton) findViewById(R.id.iv_btn_todos);
		if (btnf.getTag() == "0"){
			btnf.setImageResource(R.drawable.lst_btn_favoritos_act);	
			btnf.setTag("1");
			btnt.setImageResource(R.drawable.lst_btn_todos_des);
			btnt.setTag("0");
		}else{
			btnf.setImageResource(R.drawable.lst_btn_favoritos_des);
			btnf.setTag("0");
			btnt.setImageResource(R.drawable.lst_btn_todos_act);	
			btnt.setTag("1");
		}
	}
	
	private void muestra_detalle(int x){
		Dictionary<String,String> dic = arrGeneral.get(x);
		String tipo = dic.get("tipoF");
		String idr = "";
		String nom = "";
		
		if(tipo == null){
			return;
		}else if(tipo.equals("Patrocinadores")){
			intent = new Intent(this, PatrocinadoresDetalle.class);
			idr = dic.get("pat_idr").toString();
			nom = "idpatrocinador";
        }else if(tipo.equals("Expositores")){
        	intent = new Intent(this, ExpositoresDetalle.class);
			idr = dic.get("exp_idr").toString();
			nom = "idexpositor";
        }else if(tipo.equals("Ponencias")){
        	intent = new Intent(this, ProgramaDetalle.class);
			idr = dic.get("nen_idr").toString();
			nom = "idponencia";
        }else if(tipo.equals("Ponentes")){
        	intent = new Intent(this, PonentesDetalle.class);
			idr = dic.get("pon_idr").toString();
			nom = "idponente";
        }else if(tipo.equals("Cupones")){
        	intent = new Intent(this, Cupon_Detalle.class);
			idr = dic.get("cup_idr").toString();
			nom = "idcupon";
        }else if(tipo.equals("Eventos")){
        	intent = new Intent(this, ProgramaSocDetalle.class);
			idr = dic.get("evs_idr").toString();
			nom = "idevs";
        }else if(tipo.equals("Noticias")){
        	intent = new Intent(this, NoticiasDetalle.class);
			idr = dic.get("not_idr").toString();
			nom = "not_idr";
        }else if(tipo.equals("Lanzamientos")){
        	intent = new Intent(this, LanzamientosDetalle.class);
			idr = dic.get("lan_idr").toString();
			nom = "idlanzamiento";
		}
			
		Bundle bund = new Bundle();
		bund.putString(nom,idr);
		if(tipo.equals("Noticias")){
			bund.putString("sec_idr",dic.get("sec_idr").toString());	
		}
		intent.putExtras(bund);
		startActivity(intent);
	}
		
}
